package xyz.missou.blog.controller.manage;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import xyz.missou.blog.controller.BaseController;
import xyz.missou.blog.entity.Category;
import xyz.missou.blog.service.CategoryService;

import javax.annotation.Resource;

@Controller
@RequestMapping("/manage/category")
public class ManageCategoryController extends BaseController {

    @Resource
    private CategoryService categoryService;

    @RequestMapping({"/add/","/add"})
    public String add(Model model, RedirectAttributes redirectAttributes, @RequestParam("name") String name, @RequestParam("summary") String summary){
        Category category=categoryService.getCategoryByName(name);
        if (category==null){
            category=new Category();
            category.setName(name);
            category.setSummary(summary);
            categoryService.addCategory(category);
        }else {
            redirectAttributes.addAttribute("msg","该分类名已存在，请更换后重新添加！");
        }
        return "redirect:/manage/category/";
    }

    @RequestMapping({"/delete/{id}/","/delete/{id}"})
    public String delete(Model model, @PathVariable("id") Integer id){
        categoryService.deleteCategoryById(id);
        return "redirect:/manage/category/";
    }

    @RequestMapping({"/update/{id}/","/update/{id}"})
    public String update(Model model, RedirectAttributes redirectAttributes, @PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("summary") String summary){
        Category category=categoryService.getCategoryByName(name);
        if (category==null || category.getId()==id){
            category=new Category();
            category.setId(id);
            category.setName(name);
            category.setSummary(summary);
            categoryService.updateCategory(category);
        }else {
            redirectAttributes.addAttribute("msg","该分类名已存在，请更换后重新修改！");
        }
        return "redirect:/manage/category/";
    }
}
